package com.glodon.paas.registry.service;

import com.glodon.paas.registry.manager.X509CertManager;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import java.io.File;

import static com.google.common.base.Objects.firstNonNull;

/**
 * X509 certification service api
 *
 * @author Don Li
 */
@Service
@Path("/cert")
public class X509CertService {

    private static final Logger LOGGER = LoggerFactory.getLogger(X509CertService.class);

    @Autowired
    private X509CertManager certManager;

    @GET
    @Path("/service/{serviceId}/instance/{instanceId}")
    public Response requestInstanceCert(@PathParam("serviceId") String serviceId, @PathParam("instanceId") String instanceId) {

        String keyPwd = RandomStringUtils.randomAlphanumeric(10);
        String filePwd = RandomStringUtils.randomAlphanumeric(10);

        File certFile = certManager.createKeystoreForInstanceCertChain(serviceId, instanceId, keyPwd, filePwd);
        if (certFile != null) {
            try {
                LOGGER.info("Generate cert chain for service:{} instance:{}", serviceId, instanceId);
                // TODO safely deliver the passwords to clients
                return Response.ok().entity(certFile).type("application/x-pkcs12").build();
            } finally {
                if (certFile.exists()) {
                    certFile.deleteOnExit();
                }
            }
        }
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

    @GET
    @Path("/service/{serviceId}")
    public Response getServiceCert(@PathParam("serviceId") String serviceId, @QueryParam("pwd") String pwd) {

        String filePwd = firstNonNull(pwd, RandomStringUtils.randomAlphanumeric(10));

        File certFile = certManager.getOrCreateKeystoreForServiceCert(serviceId, filePwd);
        if (certFile != null) {
            try {
                return Response.ok().entity(certFile).type("application/x-pkcs12").build();
            } finally {
                if (certFile.exists()) {
                    certFile.deleteOnExit();
                }
            }
        }
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
}
